package com.baidu.lib_leancloud

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.leancloud.LCObject
import com.baidu.lib_leancloud.model.Advertisement
import com.baidu.lib_leancloud.model.Chart
import com.baidu.lib_leancloud.model.ChartMusicModel
import com.baidu.lib_leancloud.model.Music
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import kotlin.random.Random

class LeanCloudManager private constructor(){
    var advertisements:  List<Advertisement> = emptyList()
    var charts: List<Chart> = emptyList()
    var musics = ArrayList<Music>()
    val allMusics = MutableLiveData<List<Music>>()
    var chartMusicModelList = MutableLiveData<List<ChartMusicModel>>()
    var isNetWork = false
    companion object{
        val instance = LeanCloudManager()
    }
    fun changeIsNetWork(isNetWork: Boolean){
        this.isNetWork = isNetWork
    }
    fun loadAdv(callback:(LeanCloudManager, List<Advertisement>) -> Unit = {_,_ ->} ){
        CoroutineScope(Dispatchers.IO).launch{
            val query = LCObject.getQuery(Advertisement::class.java)
            val result = query.find()
            advertisements = result
            withContext(Dispatchers.Main){
                callback(this@LeanCloudManager,advertisements)
            }
        }
    }
    fun getRandomAdv(): Advertisement{
        val index = Random.nextInt(advertisements.size)
        return advertisements[index]
    }
    fun loadMusic(){
        CoroutineScope(Dispatchers.IO).launch{
            val query = LCObject.getQuery(Music::class.java)
            val chartMusicList = mutableListOf<ChartMusicModel>()
            //分榜单下载音乐和保存全部音乐
            for (i in charts){
                query.whereEqualTo("chart_id", i.id)
                val result = query.find()
                for (j in result){
                    musics.add(j)
                }
                chartMusicList.add(ChartMusicModel(i.chartName,result))
            }
            chartMusicModelList.postValue(chartMusicList)
            allMusics.postValue(musics)
        }
    }
    fun loadChart(callback:(LeanCloudManager, List<Chart>) -> Unit = {_,_ ->} ){
        CoroutineScope(Dispatchers.IO).launch{
            val query = LCObject.getQuery(Chart::class.java)
            val result = query.find()
            charts = result
            withContext(Dispatchers.Main){
                callback(this@LeanCloudManager,charts)
            }
        }
    }
    fun getRandomMusic(): Music{
        return musics[Random.nextInt(musics.size)]
    }
}